package com.xxkj.drugtraceability.ui.patientlist

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMFragment
import com.xxkj.drugtraceability.bean.PatientBean
import com.xxkj.drugtraceability.databinding.FragmentPatientBinding
import com.xxkj.drugtraceability.ui.doctoradvicecollection.DoctorAdviceCollectionActivity
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel


class PatientFragment : BaseVMFragment<FragmentPatientBinding>(R.layout.fragment_patient) {
    val viewModel by viewModel<PatientListViewModel>()
    val viewModelP by sharedViewModel<PatientListViewModel>()
    private lateinit var adapter: PatientAdapter
    private lateinit var layoutManager:GridLayoutManager

    companion object {
        fun newInstance(inHospState:String): PatientFragment {
            val fragment = PatientFragment()
            fragment.arguments = Bundle().apply {
                putString("inHospState", inHospState)
            }
            return fragment
        }
    }
    override fun initView() {
        arguments?.let {
            viewModel.inHospState = it.getString("inHospState", "")
        }
        binding.apply {
            adapter = PatientAdapter ()
            layoutManager = GridLayoutManager(requireContext(),2)
            recyclerView.layoutManager = layoutManager
            recyclerView.adapter = adapter
            swipe.setColorSchemeColors(resources.getColor(R.color.toolbar_background))
            swipe.setOnRefreshListener {
                viewModel.page=1
                viewModel.getPatientList(getInputWord())
            }
            recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    // Get total item count
                    if (viewModel.loadMore){
                        val totalItemCount = layoutManager.itemCount
                        // Get the last visible item position
                        val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                        // Threshold: how many items from the bottom should trigger data load
                        val loadMoreThreshold = 2
                        // Check if we are close enough to the end of the list
                        if (totalItemCount <= lastVisibleItemPosition + loadMoreThreshold) {
                            viewModel.page++
                            viewModel.getPatientList(getInputWord())
                        }
                    }
                }
            })
        }
    }

    override fun initData() {
        binding.swipe.post {
            viewModel.getPatientList(getInputWord())
        }
        adapter.setOnItemClickListener { adapter, _, position ->
            val patient = adapter.data[position] as PatientBean
            startActivity(Intent(requireContext(), DoctorAdviceCollectionActivity::class.java).putExtra("patientId",patient.patientId))
        }
    }

    override fun startObserve() {
        viewModel.uiState.observe(this, Observer {
            binding.swipe.isRefreshing = it.isRefresh
            if (it.isLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
        })
        viewModel.patientList.observe(this, Observer {
            if (it.isEmpty()){
                adapter.setEmptyView(R.layout.layout_nodata)
            }
            adapter.setList(it)
        })
    }
    public fun refreshData() {
        viewModel.page = 1
        viewModel.getPatientList(getInputWord())
    }
    fun getInputWord(): String {
        if (activity == null || activity !is PatientListActivity)
            return ""
        viewModel.depart = viewModelP.depart
        return (activity as PatientListActivity).getInputWord()
    }
}